package org.example.diary.config;

import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.diary.entity.dao.SysRole;
import org.example.diary.entity.dao.SysUser;
import org.example.diary.entity.dto.LoginUser;
import org.example.diary.enums.BizErrorCode;
import org.example.diary.exceptions.BizAssertUtil;
import org.example.diary.exceptions.SystemException;
import org.example.diary.mapper.RoleMapper;
import org.example.diary.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import java.io.IOException;
import java.util.Collections;
import java.util.Objects;

import static org.example.diary.constant.Constant.TOKEN_MAP;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private RoleMapper roleMapper;

    @Autowired
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String userInfo = "";
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userInfo = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            BizAssertUtil.isTrue(true, BizErrorCode.INVALID_API_KEY);
            SystemException systemException = new SystemException(BizErrorCode.INVALID_API_KEY.getCode(), BizErrorCode.INVALID_API_KEY.getMessage());
            resolver.resolveException(request,response,null,systemException);
            return;
        }
        SysUser sysUser = JSONObject.parseObject(userInfo, SysUser.class);
        if (Objects.isNull(sysUser) || Objects.isNull(TOKEN_MAP.get(sysUser.getId()))) {
            SystemException systemException = new SystemException(BizErrorCode.INVALID_API_KEY.getCode(), BizErrorCode.INVALID_API_KEY.getMessage());
            resolver.resolveException(request,response,null,systemException);
            return;
        }
        String mapToken = TOKEN_MAP.get(sysUser.getId());
        if (Objects.isNull(mapToken) || !mapToken.equals(token)){
            SystemException systemException = new SystemException(BizErrorCode.INVALID_API_KEY.getCode(), BizErrorCode.INVALID_API_KEY.getMessage());
            resolver.resolveException(request,response,null,systemException);
            return;
        }

        SysRole sysRole = roleMapper.selectById(sysUser.getRole());

        LoginUser loginUser = new LoginUser(sysUser, Collections.singletonList(sysRole.getName()));
        // 参数：1、用户名   2、密码   3、权限
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }


}

